const RoleCheck = {};
RoleCheck.install = function (Vue) {
  Vue.mixin({
    data() {
      return {
        checkedRole: [],
        roles: undefined,
      };
    },
    methods: {
      roleCheck(value) {
        if (this.roles == undefined) {
          const route = this.$route;
          this.roles = route && route.meta && route.meta.roles || [];// 消除对route的依赖
          // console.log(this._uid)
        }
        // console.log(this._uid)
        let flag = true;
        let includeRole = [];
        let excludeRole = [];
        const checked = _.find(this.checkedRole, item => item == value);
        // 如果指令中指定了权限要求&& !checked
        if (value && !checked) {
          if (typeof value === 'string') {
            includeRole = [value];
          } else if (Array.isArray(value)) {
            includeRole = value;
          } else if (typeof value === 'object') {
            includeRole = value.include || [];// 部分操作同时承担显示的功能，所以对同一权限增加exclude反向定义，表示无相应操作时的展示
            excludeRole = value.exclude || [];
            if (typeof includeRole === 'string') {
              includeRole = [includeRole];
            }
            if (typeof excludeRole === 'string') {
              excludeRole = [excludeRole];
            }
          }
          if (Array.isArray(includeRole) && Array.isArray(excludeRole)) {
            if ((includeRole.length > 0 && _.intersection(this.roles, includeRole).length == 0) || _.intersection(this.roles, excludeRole).length > 0) {
              flag = false;
            }
          }
        }
        if (flag && !checked && typeof value === 'string') {
          this.checkedRole.push(value);
        }
        return flag;
      },
      dataRoleCheck(value) {
        const flattenedPermission = this.formatPermissionList(this.dataPermissionList);
        const checkItem = _.find(flattenedPermission, { keyword: value });
        if (checkItem) {
          return true;
        }
        return false;
      },
      formatPermissionList(permissionList) {
        let flattenedPermission = [];
        _.each(permissionList, (item) => {
          flattenedPermission.push(item);
          if (item.children) {
            flattenedPermission = flattenedPermission.concat(this.formatPermissionList(item.children));
          }
        });
        return flattenedPermission;
      },
    },
    computed: {
      ...mapState({
        dataPermissionList: state => state.permission.dataPermissionList,
      }),
    },
  });
};
export default RoleCheck;
